import {_decorator, Component, instantiate, Node, UITransform, Vec2} from 'cc';
import {ResourcesUtil} from "db://assets/script/utils/ResourcesUtil";
import {SettingManager} from "db://assets/script/modules/SettingManager";
import {ClickMoveController} from "db://assets/script/core/ClickMoveController";
import {MapController} from "db://assets/script/core/MapController";

const {ccclass, property} = _decorator;

type MonsterType = {
    name: string
    probabilityOfAppearance: number
}

@ccclass('SceneManager')
export class SceneManager extends Component {
    /**
     * 当前地图名
     */
    public static currentMapKey: string = 'test'
    /**
     * 地图父节点
     */
    public static mapNode: Node = null
    /**
     * 地图节点
     */
    public static currentMapNode: Node = null
    /**
     * 加载节点
     */
    public static loadingNode: Node = null
    /**
     * 加载节点show时的时间戳
     */
    public static lastLoadingTime: number = 0
    /**
     * 从json文件读取的当前地图上的所有怪物数据
     */
    public static monsterData: MonsterType[] = []
    /**
     * 领地数据
     */
    public static territoryData: Record<string, Vec2[]>
    /**
     * 加载地图show时持续的最短时间
     */
    public static readonly minLoadingTime: number = 2000
    /**
     * 生成怪物的固定数量 因为向上去整 实际情况会多
     */
    public static readonly monsterTotal: number = 10


    public static setCurrentMapKey(key: string) {
        this.currentMapKey = key
    }

    public static setCurrentMapNode(node: Node) {
        this.currentMapNode = node
    }

    public static setLoadingNode(node: Node) {
        this.loadingNode = node
    }

    public static setMapNode(node: Node) {
        this.mapNode = node
    }

    public static setTerritoryData(data: Record<string, Vec2[]>) {
        this.territoryData = data
    }

    /**
     * 初始化怪物
     */
    public static async initMonster() {
        try {
            // console.log(this.currentMapKey)
            const key = this.currentMapKey
            // 加载地图怪物
            const json: Record<string, MonsterType[]> = await ResourcesUtil.loadJson(`jsons/${key}`)
            // 存储数据
            const monsters = json.data
            this.monsterData = json.data

            // 随机生成怪物计算
            const totalProbabilityOfAppearance = monsters.reduce((acc, monster) => acc + monster.probabilityOfAppearance, 0)
            const totalMonsterTotal = this.monsterTotal

            type GeneratedMonsterType = {
                name: string
                pos: Vec2
            }

            const generatedMonsters: GeneratedMonsterType[] = []
            const territoryData = this.territoryData
            for (let i = 0; i < totalMonsterTotal; i++) {
                // 生成[0, totalProbability)之间的随机数
                const random = Math.random() * totalProbabilityOfAppearance;
                // 累计概率区间查找
                let accumulated = 0;
                for (const monster of monsters) {
                    accumulated += monster.probabilityOfAppearance;
                    const territoryList = territoryData[monster.name]
                    if (random < accumulated) {
                        const randomIndex = Math.floor(Math.random() * territoryList.length)
                        generatedMonsters.push({name: monster.name, pos: territoryList[randomIndex]});
                        break; // 找到后跳出循环
                    }
                }
            }

            for (let i = 0; i < generatedMonsters.length; i++) {
                const generatedMonster = generatedMonsters[i]
                const key = generatedMonster.name
                // 加载目标地图
                const prefab = await ResourcesUtil.loadPrefab(`prefabs/${key}`)
                // 实例化预制体
                const mapInstance = instantiate(prefab);
                if (!mapInstance) {
                    console.log('怪物实例化失败');
                    return;
                }
            }


        } catch (e) {
            console.log('报错', e)
        }
    }

    /**
     * 初始化地图
     * @param key
     */
    public static async initMap(key: string) {
        try {
            this.showLoading()
            this.setCurrentMapKey(key)

            if (this.currentMapNode) {
                this.currentMapNode.destroy()
                // 清除旧地图
                this.mapNode.removeAllChildren()
            }

            // 加载目标地图
            const prefab = await ResourcesUtil.loadPrefab(`prefabs/${key}`)
            // 实例化预制体
            const mapInstance = instantiate(prefab);
            if (!mapInstance) {
                console.log('地图实例化失败');
                return;
            }
            const contentSize = mapInstance.getComponent(UITransform).contentSize
            // console.log('SettingManager.controlType', SettingManager.controlType)
            if (SettingManager.controlType === 'click') {
                mapInstance.addComponent(ClickMoveController)
            }
            mapInstance.addComponent(MapController)

            this.mapNode.parent.getComponent(UITransform).setContentSize(contentSize.width, contentSize.height)
            this.mapNode.getComponent(UITransform).setContentSize(contentSize.width, contentSize.height)
            this.mapNode.addChild(mapInstance)

            // 把当前地图存起来
            this.setCurrentMapNode(mapInstance)
        } catch (e) {
            console.log('报错', e)
        }
    }

    public static showLoading() {
        this.lastLoadingTime = new Date().getTime();
        this.loadingNode.active = true
    }

    public static hiddenLoading() {
        console.log('hiddenLoading')
        const nowTime = new Date().getTime();
        if (this.lastLoadingTime === 0) {
            setTimeout(() => {
                console.log('false')
                this.loadingNode.active = false
            }, 1000)
            return
        }
        const diffTime = nowTime - this.lastLoadingTime
        if (diffTime < this.minLoadingTime) {
            setTimeout(() => {
                this.loadingNode.active = false
            }, this.minLoadingTime - diffTime)
        } else {
            this.loadingNode.active = false
        }
    }
}


